#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "type.h"
#include "log.h"
#include "errorcode.h"

INT32 main(INT32 argc, INT8 **argv)
{
    INT32 sockfd;
    INT32 n;
    char recvline[512];
    
    struct sockaddr_in servaddr;

    if (2 != argc)
    {
        LOG_ERROR("usage: ./%s <ipaddress>", argv[0]);
        return ERR_INVALID_PARA;
    }

    log_init();
    
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        LOG_ERROR("socket error, errno(%d), errstr(%s)", errno, strerror(errno));
        return ERR_SOCKET_CREATE;
    }

    memset(&servaddr, 0, sizeof(struct sockaddr_in));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port   = htons(13);

    if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
    {
        LOG_ERROR("inet_pton error, errno(%d), errstr(%s)", errno, strerror(errno));
        return ERR_ERROR;
    }

    if ((connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(struct sockaddr_in))) < 0)
    {
        LOG_ERROR("connect error, errno(%d), errstr(%s)", errno, strerror(errno));
        return ERR_ERROR;
    }
    
    while ((n = read(sockfd, recvline, 512 - 1)) > 0)
    {
        recvline[n] = 0;
        if (fputs(recvline, stdout) == EOF)
        {
            LOG_ERROR("fputs error");
            return ERR_ERROR;
        }
    }

    if (n < 0)
    {
        LOG_ERROR("read error, errno(%d), errstr(%s)", errno, strerror(errno));
        return ERR_SOCKET_RECV;
    }

    return 0;
}
